package com.zx.ishopping.aspect;

import com.zx.ishopping.Constants.AutoFillConstant;
import com.zx.ishopping.annotation.AutoFill;
import com.zx.ishopping.enums.OperationEnum;
import com.zx.ishopping.utils.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Aspect
@Component
@Slf4j
public class AutoFillAspect {

    //1.定义切入点，定义哪些方法需要拦截
    @Pointcut("execution(* com.zx.ishopping.mapper.*.*(..))&&@annotation(com.zx.ishopping.annotation.AutoFill)")
    public void autoFillPointCut(){

    }

    //2.定义通知，在方法执行前进行公共字段填充
    @Before("autoFillPointCut()")
    public void autoFill(JoinPoint joinPoint){
        log.info("开始进行公共字段填充");
        
        
        //获取当前被拦截方法上的数据库类型
        //方法签名对象
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        //获取方法上的注解对象
        AutoFill autoFill = signature.getMethod().getAnnotation(AutoFill.class);
        //获取数据库操作类型
        OperationEnum operationEnum = autoFill.value();
        
       //获取到当前的被拦截的方法参数，实体对象
        Object[] args = joinPoint.getArgs();
        if(args == null || args.length == 0){
            return;
        }
        Object entity = args[0];

        LocalDateTime now = LocalDateTime.now();

        //根据对应的数据库操作类型，为对应的字段赋值
        if(operationEnum == OperationEnum.INSERT){
            //为四个公共字段赋值
            
            try {
                Method setCreateTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
                Method setUpdateTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
                //通过反射为对象属性赋值
                setCreateTime.invoke(entity,now);
                setUpdateTime.invoke(entity,now);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        
        if (operationEnum == OperationEnum.UPDATE){
            try {
                Method setUpdateTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
                //通过反射为对象属性赋值
                setUpdateTime.invoke(entity,now);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
       
        
            
        }

    }

